'''
redis缓存相关操作

'''

import redis
import threading

class RedisOpt(object):

    # 防止单例模式的多线程下实例化出现问题，枷锁
    _instance_lock = threading.Lock()
    def __init__(self):
        self.__pool = redis.ConnectionPool(host='localhost', port=6379, db=1)
    pass

    @classmethod
    def get_instance(self):
        if not hasattr(RedisOpt,'_instance'):
            with RedisOpt._instance_lock:
                if not hasattr(RedisOpt,'_instance'):
                    RedisOpt._instance = RedisOpt()
        return RedisOpt._instance

    def key_expire(self,name,expire):
        red = redis.Redis(connection_pool=self.__pool)
        red.expire(name,expire)

    # 设值
    def s_set(self,key,value,expire=None):
        red = redis.Redis(connection_pool=self.__pool)
        red.set(key,value,ex=expire)
        pass

    # 获取值
    def s_get(self,key):
         red = redis.Redis(connection_pool = self.__pool)
         value = red.get(key)

         if value is not None:
             value = value.decode('UTF-8')

         return value

    def key_del(self,key):
        red = redis.Redis(connection_pool=self.__pool)
        red.delete(key)

    # 将一个值或多个值放进列表尾
    def l_rpush(self,name,*values):
        red = redis.Redis(connection_pool=self.__pool)
        red.rpush(name,*values)

    # 获取列表选定区间的元素
    def l_range(self,name,start,stop):
        red = redis.Redis(connection_pool=self.__pool)
        return red.lrange(name,start,stop)

    #移除并返回列表 name 的头元素
    def l_lpop(self,name):
        red = redis.Redis(connection_pool=self.__pool)
        return red.lpop(name)

    # 列表长度
    def l_len(self,name):
        red = redis.Redis(connection_pool=self.__pool)
        return red.llen(name)

    #移除并返回列表name的尾元素
    def l_rpop(self,name):
        red = redis.Redis(connection_pool=self.__pool)
        return red.rpop(name)

pass

class RedisConstant:
    # 代理ip key
    PROXY_IP_89_LIST_KEY = 'l_proxy_ip_89'

    # 代理IP运行的状态 1：有效 0：无效
    JIAYUAN_PORXY_STATUS = 's_jiayuan_proxy_status'

    #代理爬虫运行状态 0：空闲，1;正在运行
    PROXY_IP_89_RUN_STATUS = 's_proxy_ip_89_run_status'

    JIAYUAN_USER_LIST_KEY = 'l_jiayuan_user_list'

    @classmethod
    def proxy89ip_list_item_format(self,ipvalue,portvalue):
        return '{}:{}'.format(ipvalue,portvalue)